<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
    </el-row>

    <el-table v-if="refreshTable" v-loading="loading" :data="deptList" row-key="id" lazy :load="load"
      :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column prop="cityName" :label="$t('licence.city_name_cn')" width="280"> </el-table-column>
      <el-table-column prop="regionNameEn" :label="$t('licence.city_name_en')" width="280"> </el-table-column>

      <el-table-column :label="$t('licence.city_operate')" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:dept:edit']">{{
            $t('licence.edit') }}</el-button>
          <el-button v-if="scope.row.type < 3" type="text" icon="Plus" @click="handleAdd(scope.row)"
            v-hasPermi="['system:dept:add']">{{ $t('licence.use_handleAdd') }}</el-button>
          <el-button v-if="scope.row.pid != 0" type="text" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:dept:remove']">{{ $t('licence.del') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改区域对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="formref" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('licence.city_name_cn')" prop="cityName">
              <el-input v-model="form.cityName" :placeholder="$t('licence.city_name_cn')" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('licence.city_name_en')" prop="regionNameEn">
              <el-input v-model="form.regionNameEn" :placeholder="$t('licence.city_name_en')" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('licence.city_longitude')" prop="longitude">
              <el-input v-model="form.longitude" :placeholder="$t('licence.city_longitude')" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('licence.city_latitude')" prop="latitude">
              <el-input v-model="form.latitude" :placeholder="$t('licence.city_latitude')" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('licence.determine') }}</el-button>
        <el-button @click="cancel">{{ $t('licence.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name='City' lang="ts">
import { listDept, getDept, delDept, addDept, updateDept, getChildren } from '@/api/system/city/city';
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 遮罩层
const loading = ref(true)
// 表格树数据
const deptList = ref([])
// 弹出层标题
const title = ref('')
// 是否显示弹出层
// 查询参数
const queryParams = ref({
  cityName: undefined,
  status: undefined,
  code: 0,
})
const userInfo = ref({
      dept:{code:'',deptName:'',countryCode:0},
      sex:0,
      email:'',
      nickName:'',
      userName:'',
      phonenumber:112,
    });//用户信息
const open = ref(false)
// 是否展开，默认全部展开
const isExpandAll = ref(false)
// 重新渲染表格状态
const refreshTable = ref(true)
// 表单参数
const form = ref({})
const formref = ref()
// 表单校验
const rules = {
  pid: [{ required: true, message: '上级区域不能为空', trigger: 'blur' }],
  cityName: [{ required: true, message: 'Region name cannot be empty', trigger: 'blur' }],
  regionNameEn: [{ required: true, message: 'Region name cannot be empty', trigger: 'blur' }],
}
const lang = ref('')

onMounted(() => {
  // 获取语言
  if (localStorage.getItem('locale') == 'en_US') {
    lang.value = '1';
  } else {
    lang.value = '0';
  }
  // 获取用户信息
  userInfo.value = JSON.parse(localStorage.getItem('userInfo') as string);
  getList();
})

/** 查询区域列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.code = userInfo.value.dept.countryCode;
  listDept(queryParams.value).then((response) => {
    deptList.value = response.data;
    loading.value = false;
  });
}
// 点击进行懒加载
const load = async (tree?:any, treeNode?:any, resolve?:any) => {
  try {
    let { code, data } = await getChildren(tree.id);
    if (code == 200) {
      resolve(data);
    }
  } catch (error) {
    console.log(error);
  }
}
/** 转换区域数据结构 */
const normalizer = (node:any) => {
  if (node.children && !node.children.length) {
    delete node.children;
  }
  return {
    id: node.id,
    label: node.cityName,
    children: node.children,
  };
}
// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
}
// 表单重置
const reset = () => {
  form.value = {
    id: undefined,
    pid: undefined,
    cityName: undefined,
    regionNameEn: undefined,
    orderNum: undefined,
    leader: undefined,
    phone: undefined,
    email: undefined,
    lang: '0',
    status: '0',
  };
  formref.value?.clearValidate()
  formref.value?.resetFields()
}

/** 新增按钮操作 */
const handleAdd = (row: any) => {
  reset();
  queryParams.value.code = userInfo.value.dept.countryCode;
  if (row != undefined) {
    form.value.pid = row.id;
  }
  open.value = true;
  title.value = t('licence.city_add');
}
/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}
/** 修改按钮操作 */
const handleUpdate = (row:any) => {
  reset();
  getDept(row.id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = t('licence.city_modify');
  });
}
/** 提交按钮 */
const submitForm = () => {
  formref.value?.validate((valid:any) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateDept(form.value).then((response) => {
          proxy?.$modal.msgSuccess(t('licence.success'));
          open.value = false;
          load();
        });
      } else {
        addDept(form.value).then((response) => {
          proxy?.$modal.msgSuccess(t('licence.success'));
          open.value = false;
          load();
        });
      }
    }
  });
}
/** 删除按钮操作 */
const handleDelete = (row: any) => {
  proxy?.$modal
    .confirm(t('licence.common_delete'))
    .then(function () {
      return delDept(row.id, lang.value);
    })
    .then(() => {
      proxy?.$modal.msgSuccess(t('licence.common_delete_success'));
      load();
    })
    .catch(() => { });
}

</script>
